<script setup>
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { usePage } from '@inertiajs/vue3'
import MobileNavigation from './MobileNavigation.vue'
import DesktopNavigation from './DesktopNavigation.vue'
import ThemeToggle from './ThemeToggle.vue'
import AvatarContainer from './AvatarContainer.vue'
import Avatar from './Avatar.vue'
import Container from './Container.vue'

const props = defineProps({
  navigation: {
    type: Array,
    default: () => []
  }
})

const page = usePage()
const isHomePage = computed(() => route().current('blog.home') ?? page.url === '/')

const headerRef = ref(null)
const avatarRef = ref(null)
const isInitial = ref(true)

// Clamp function
const clamp = (number, a, b) => {
  const min = Math.min(a, b)
  const max = Math.max(a, b)
  return Math.min(Math.max(number, min), max)
}

// Set CSS property
const setProperty = (property, value) => {
  document.documentElement.style.setProperty(property, value)
}

// Remove CSS property
const removeProperty = (property) => {
  document.documentElement.style.removeProperty(property)
}

let downDelay = 0
let upDelay = 64

const updateHeaderStyles = () => {
  const headerEl = headerRef.value
  if (!headerEl) {
    return
  }

  try {
    const { top, height } = headerEl.getBoundingClientRect()
    const scrollY = clamp(
      window.scrollY,
      0,
      document.body.scrollHeight - window.innerHeight,
    )

    // 非首页时，downDelay 应该为 0 或 header 高度
    const effectiveDownDelay = isHomePage.value ? downDelay : 0

    if (isInitial.value) {
      setProperty('--header-position', 'sticky')
    }

    setProperty('--content-offset', `${effectiveDownDelay}px`)

    // 使用容差避免边界抖动（约 1px 的容差）
    const tolerance = 1

    if (isInitial.value || scrollY < effectiveDownDelay) {
      setProperty('--header-height', `${effectiveDownDelay + height}px`)
      setProperty('--header-mb', `${-effectiveDownDelay}px`)
    } else if (top + height < -upDelay) {
      const offset = Math.max(height, scrollY - upDelay)
      setProperty('--header-height', `${offset}px`)
      setProperty('--header-mb', `${height - offset}px`)
    } else if (Math.abs(top) < tolerance) {
      setProperty('--header-height', `${scrollY + height}px`)
      setProperty('--header-mb', `${-scrollY}px`)
    }

    // 使用容差判断是否应该使用 fixed 定位
    const shouldBeFixed = Math.abs(top) < tolerance && scrollY > tolerance && scrollY >= effectiveDownDelay

    if (shouldBeFixed) {
      setProperty('--header-inner-position', 'fixed')
      removeProperty('--header-top')
      removeProperty('--avatar-top')
    } else {
      removeProperty('--header-inner-position')
      setProperty('--header-top', '0px')
      setProperty('--avatar-top', '0px')
    }
  } catch (e) {
    // 忽略错误，等待下次调用
  }
}

const updateStyles = () => {
  updateHeaderStyles()
  isInitial.value = false
}

let rafId = null
const handleScroll = () => {
  if (rafId !== null) {
    return
  }
  rafId = requestAnimationFrame(() => {
  updateStyles()
    rafId = null
  })
}

const handleResize = () => {
  if (avatarRef.value) {
    downDelay = avatarRef.value.offsetTop ?? 0
  }
  updateStyles()
}

onMounted(() => {
  nextTick(() => {
    if (avatarRef.value) {
      downDelay = avatarRef.value.offsetTop ?? 0
    }
    updateStyles()
  })
  window.addEventListener('scroll', handleScroll, { passive: true })
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
  window.removeEventListener('resize', handleResize)
  if (rafId !== null) {
    cancelAnimationFrame(rafId)
    rafId = null
  }
})
</script>

<template>
  <header
    class="pointer-events-none relative z-50 flex flex-none flex-col"
    :style="{
      height: 'var(--header-height)',
      marginBottom: 'var(--header-mb)',
    }"
  >
    <!-- Avatar on home page -->
    <template v-if="isHomePage">
      <div
        ref="avatarRef"
        class="order-last mt-[calc(4rem-0.75rem)]"
      />
      <Container
        class="top-0 order-last -mb-3 pt-3"
        :style="{
          position: 'var(--header-position)',
        }"
      >
        <div
          class="top-[var(--avatar-top,0.75rem)] w-full"
          :style="{
            position: 'var(--header-inner-position)',
          }"
        >
          <div class="relative">
            <!-- <Avatar
              :large="true"
              class="block h-16 w-16"
            /> -->
          </div>
        </div>
      </Container>
    </template>

    <!-- Main header -->
    <div
      ref="headerRef"
      class="top-0 z-10 h-16 pt-6"
      :style="{
        position: 'var(--header-position)',
      }"
    >
      <Container
        class="top-[var(--header-top,1.5rem)] w-full"
        :style="{
          position: 'var(--header-inner-position)',
        }"
      >
        <div class="relative flex gap-4">
          <div class="flex flex-1">
            <div class="pointer-events-auto">
              <AvatarContainer>
                <Avatar />
              </AvatarContainer>
            </div>
          </div>
          <div class="flex flex-1 justify-end md:justify-center">
            <MobileNavigation
              class="pointer-events-auto md:hidden"
              :items="props.navigation"
            />
            <DesktopNavigation
              class="pointer-events-auto hidden md:block"
              :items="props.navigation"
            />
          </div>
          <div class="flex justify-end md:flex-1">
            <div class="pointer-events-auto flex items-center gap-3">
              <slot name="actions" />
              <ThemeToggle />
            </div>
          </div>
        </div>
      </Container>
    </div>
  </header>

  <!-- Content offset for home page -->
  <div
    v-if="isHomePage"
    class="flex-none"
    :style="{ height: 'var(--content-offset)' }"
  />
</template>
